package cn.com.ksplatform.modules.system.auth.loginmanager.filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import cn.com.ksplatform.common.logger.Log;
import cn.com.ksplatform.core.context.PlatformContext;
import cn.com.ksplatform.modules.system.auth.loginmanager.controller.LoginCons;

//@WebFilter(urlPatterns="/*")
public class LoginFilter extends OncePerRequestFilter{
	
	LoginIgoneUrls igones;
	
	public LoginFilter() {
		igones = PlatformContext.getBean("system.modules.system.fiter.IgoneUrls",LoginIgoneUrls.class);
		Log.info("LoginFilter初始化完成");
	}
	
	@Override
	protected void doFilterInternal(HttpServletRequest arg0,
			HttpServletResponse arg1, FilterChain arg2)
			throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse reponse = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		
		//忽略拦截资源
		Set<String> igorns = igones.getIgorns();
		Set<String> igorn_prefix = igones.getIgorn_prefix();
		Set<String> igorn_path = igones.getIgorn_path();
		
		String uri = request.getRequestURI();
		String path = request.getContextPath();
		boolean pass = (session.getAttribute(LoginCons.LOGIN_USER) != null);
		
		
		
		if(!pass){
			for(String igorn : igorn_path){
				if(uri.startsWith(path+igorn)){
					pass = true;
					break;
				}
			}
			for(String igorn : igorn_prefix){
				if(uri.endsWith(igorn)){
					pass = true;
					break;
				}
			}
			for(String igorn : igorns){
				if(uri.equals(path+igorn)){
					pass = true;
					break;
				}
			}
		}
		
		if(pass){
			arg2.doFilter(arg0, arg1);
		}else{
			try {
				Class.forName("cn.com.ksplatform.modules.sso.filter.SessionFilter");
				reponse.sendRedirect(request.getContextPath()+"/view/modules/system/index.vm");
			} catch (ClassNotFoundException e) {
				reponse.sendRedirect(request.getContextPath()+"/view/modules/system/login.vm");
			}
		}
		
	}
}